﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _01_OOP
{
   
    /// <summary>
    /// 相等性
    /// </summary>
    internal class EqualsExample
    {
        public class Student
        {

            public int ID { get; set; }
            public string? Name { get; set; }

            public Student(int iD, string? name)
            {
                ID = iD;
                Name = name;
            }

            public static bool operator ==(Student a, Student b)
            {
                return Equals(a, b);
            }

            public static bool operator !=(Student a, Student b)
            {
                return !Equals(a, b);
            }

            public override bool Equals(object? obj)
            {
                if (ReferenceEquals(this, obj))
                {
                    return true;
                }

                if (ReferenceEquals(obj, null))
                {
                    return false;
                }

                if (obj is not Student)
                {
                    return false;
                }

                var student = obj as Student;
                if (student?.ID == this.ID)
                {
                    return true;
                }
                return false;
            }

            public override int GetHashCode()
            {
                return ID.GetHashCode();
            }
        }
        public class Teacher
        {

            public int ID { get; set; }
            public string? Name { get; set; }

            public Teacher(int iD, string? name)
            {
                ID = iD;
                Name = name;
            }

        }
        public static void Test(string[] args)
        {
            //student
            Student s1 = new Student(1, "zs");
            Student s2 = new Student(1, "zs");
            Console.WriteLine(s1 == s2);
            Console.WriteLine(s1.Equals(s2));
            //只要new，引用就不相等
            Console.WriteLine(ReferenceEquals(s1, s2));
            //运算符重载只与引用的类型相关
            object o1 = s1;
            object o2 = s2;
            Console.WriteLine(o1 == o2);
            Console.WriteLine(o1.Equals(o2));
            Console.WriteLine(ReferenceEquals(o1, o2));
            Console.WriteLine(ReferenceEquals(o1, s1));
            //teacher
            Teacher t1 = new Teacher(1, "zs");
            Teacher t2 = new Teacher(1, "zs");
            Console.WriteLine(t1 == t2);//比较引用
            Console.WriteLine(t1.Equals(t2));//比较引用
            //string：常量池
            var str1 = "123";
            var str2 = "123";
            Console.WriteLine(str1 == str2);//string重写了==
            Console.WriteLine(str1.Equals(str2));
            Console.WriteLine(ReferenceEquals(str1, str2));//true:因为指向同一个常量
        }
    }
}
